/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.stdlib.money.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.api.Formatting;
import axil.api.Persona;
import axil.framework.config.Configuration;
import axil.stdlib.core.type.Atom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * The Axil object representing currency. Axil only supports the currencies
 * for which you have configured support.
 */
public class Currency extends Atom {
	public static final AxilType type = Currency_Type.object;
	private static final List<Currency> supported = new ArrayList<Currency>();
	private static final Map<Character,Currency> prefixes =
	    new HashMap<Character, Currency>();
	private static final Map<String,Currency> suffixes =
	    new HashMap<String, Currency>();
	static {
		for (String iso :
		        Configuration.axil().list("supported-currencies", false)) {
			Configuration cfg = new Configuration(
			    "data/currency/" + iso + ".cfg");
			Currency c = new Currency(cfg);
			supported.add(c);
			prefixes.put(c.symbol, c);
			suffixes.put(c.iso, c);
		}
	}

	private String iso;		// ISO 4701 currency code, such as "USD"
	private char symbol;	// Unicode sequence for prefix, such as "$"
	private int fractional;	// Fractional digits normally displayed
	private java.util.Currency currency;


	private Currency(Configuration cfg) {
		iso = cfg.text("iso-code");
		symbol = cfg.text("currency-symbol").charAt(0);
		fractional = cfg.integer("fractional-digits");
		currency = java.util.Currency.getInstance(iso);
	}


	/**
	 * Get the type metadata for this object. The type metadata contains
	 * information about the type itself, as an object.
	 */
	public AxilType type() {
		return type;
	}


	/**
	 * Get a currency based upon the currency symbol, such as '$'. If the symbol
	 * is not a valid currency symbol, or that is not one of the supported
	 * locales for the host application, then a null is returned.
	 */
	public static Currency from(char symbol) {
		return prefixes.get(symbol);
	}


	/**
	 * Get the currency from the indicated ISO 4701 currency code. If the code
	 * is not a valid ISO code, or that code is not one of the supported locales
	 * for the host application, then a null is returned.
	 */
	public static Currency from(String iso) {
		return suffixes.get(iso);
	}


	public String iso() {
		return iso;
	}


	public char symbol() {
		return symbol;
	}


	public int fractional() {
		return fractional;
	}


	public java.util.Currency currency() {
		return currency;
	}


	/**
	 * Returns a hash code value for the object. All Axil values must provide a
	 * meaningful implementation of this function to enable themselves to be
	 * placed in a map or set.
	 */
	protected int hash() {
		return iso.hashCode();
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.  If
	 * the given object is not a suitable type for comparison, a
	 * ClassCastException may be thrown.
	 */
	public boolean equalTo(AxilObject object) {
		return this == object;
	}


	/**
	 * Compares this object with the specified object for order. If the given
	 * object is not a suitable type for comparison, a ClassCastException may
	 * be thrown.
	 *
	 * @param object
	 * 	The object to compare against. The given object cannot be null but may
	 * 	be any Axil object.
	 *
	 * @return
	 * 	Returns a negative integer, zero, or a positive integer as this object
	 * 	is less than, equal to, or greater than the specified object.
	 */
	public int comparedTo(AxilObject object) {
		return iso.compareTo(((Currency)object).iso);
	}


	/**
	 * Format this object in a locale-friendly manner. The string returned is
	 * a localized representation of this object using the locale and timezone
	 * associated with this persona. The formatting given is never null and
	 * matches formatting suitable for this type.
	 */
	public String format(Persona persona, Formatting formatting) {
		return iso;
	}


	public static Currency any() {
		return supported.get(0);
	}


	/**
	 * Return a string containing all of the unique currency symbol characters
	 * (such as '$').
	 */
	public static String symbols() {
		StringBuilder symbols = new StringBuilder();
		for (Currency c : all()) {
			if (! contains(symbols, c.symbol)) {
				symbols.append(c.symbol());
			}
		}
		return symbols.toString();
	}


	private static boolean contains(StringBuilder text, char ch) {
		final int size = text.length();
		for (int i = 0; i < size; i++) {
			if (text.charAt(i) == ch) {
				return true;
			}
		}
		return false;
	}


	public static List<Currency> all() {
		return supported;
	}


	/**
	 * Return a string representation of this object. The string returned is
	 * never null.
	 */
	public String toString() {
		return iso();
	}
}
